package com.jingxuan.util;

import java.nio.charset.StandardCharsets;

import cn.hutool.core.util.RandomUtil;
import org.springframework.util.DigestUtils;

import com.jingxuan.common.exception.BusinessException;
import com.jingxuan.common.result.ResultCode;
/**
 * MD5加密工具类
 */
public class MD5Util {
    public static String encode(String pwd){
        // 生成盐
        String salt = RandomUtil.randomString(20);
        // 凭借盐和密码
        return encode(pwd,salt);
    }

    public static String encode(String pwd,String salt){
        // 加密
        return salt + "@" + DigestUtils.md5DigestAsHex((pwd+salt).
        getBytes(StandardCharsets.UTF_8));
    }

    public static boolean verify(String encodedPwd,String rawPwd){
        if(encodedPwd == null || rawPwd == null){
            return false;
        }
        if(!encodedPwd.contains("@")){
            throw new BusinessException(ResultCode.PARAM_ERROR,"密码格式错误");
        }
        String[] parts = encodedPwd.split("@");
        // 获取盐
        String salt = parts[0];
        // 验证
        return encodedPwd.equals(encode(rawPwd,salt));
    }
}

